/*
 * Copyright (c) 2011. c.mueller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package de.altitude.cimuelle.utils;

import de.altitude.cimuelle.Config;
import de.altitude.cimuelle.MessageBundle;
import de.altitudecustomcommands.serverInformations;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import javax.naming.ConfigurationException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

/**
 * Class description:
 * <p/>
 * User: cybernaut
 * Date: 07.10.11
 * Time: 22:35
 */
public class ServerOperations {
    private static final Logger LOGGER = Logger.getLogger("ServerOperations");
    @SuppressWarnings({"FieldCanBeLocal"})
    private static final String version = "0.04v";

    public static void sendServerMessage(String port, String completeMessage) {
        String[] messages = completeMessage.split("\\n");
        for (String message : messages) {
            StringBuilder sb = new StringBuilder();
            sb.append(port).append(",console,serverMessage ").append(message);
            sendCommand(sb.toString());
        }
    }

    public static void sendServerWhisper(String port, String nickname, String completeMessage) {
        String[] messages = completeMessage.split("\\n");
        for (String message : messages) {
            StringBuilder sb = new StringBuilder();
            sb.append(port).append(",console,serverWhisper \"").append(StringUtils.addslashes(nickname)).append("\" ").append(message);
            sendCommand(sb.toString());
        }
    }

    public static synchronized void sendCommand(String command) {
        BufferedWriter write;
        try {
            if (Config.getInstance().isDebug()) {
                LOGGER.debug("Send command: " + command);
            }
            LOGGER.info("Sending command: " + command);

            write = new BufferedWriter(new FileWriter(new File(Config.getInstance().getCommandFile()), true));
            write.append(command);
            write.newLine();
            write.flush();
            write.close();
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
    }

    public synchronized static void sendSingleCommand(String command) throws ConfigurationException {
        BufferedWriter write;
        Config prop = Config.getInstance();
        try {
            if ("true".equals(prop.getConfig("appendTimeToCommand", "false"))) {
                command = Calendar.getInstance().getTime().toString() + " : " + command;
            }
            if (prop.isDebug()) {
                LOGGER.debug(command);
            }
            write = new BufferedWriter(new FileWriter(new File(prop.getCommandFile()), true));
            write.append(command);
            write.newLine();
            write.flush();
            write.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static synchronized void sendServerStatusCommand() {
        String listPlayerCommand = ",console,logServerStatus";
        serverInformations sserver;
        try {
            sserver = new serverInformations();
            for (int i = 0; i < sserver.getServerNumber(); i++) {
                int serverPort = sserver.getServer(i).getPort();
                if (Config.getInstance().isGetConfigByPort(String.valueOf(serverPort), "active", "false")) {
                    LOGGER.info("Sending logServerStatus command to server: " + serverPort);
                    sendSingleCommand(serverPort + listPlayerCommand);
                    if (Config.getInstance().isGetConfigByPort(String.valueOf(serverPort), "coopRankingActive", "false")) {
                        LOGGER.info("Sending intial Coop-Change Map notice.");
                        sendServerMessage(String.valueOf(serverPort), MessageBundle.getString("scoopProgramStart", "VERSION", version));
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            LOGGER.error(e, e);
        } catch (SAXException e) {
            e.printStackTrace();
            LOGGER.error(e, e);
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error(e, e);
        } catch (ConfigurationException e) {
            e.printStackTrace();
            LOGGER.error(e, e);
        }
    }

}
